import React, { useState, useRef } from 'react';
import {
    Container,
    Box,
    Typography,
    Button,
    Paper,
    Breadcrumbs,
    Link as MuiLink,
    Divider,
    Grid,
    Alert,
    AlertTitle
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ModelTraining as ModelIcon,
    FileUpload as FileUploadIcon
} from '@mui/icons-material';
import { Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';

import { useModelContext } from '../contexts/ModelContext';
import ModelForm from '../components/ModelForm';
import FileUpload from '../components/FileUpload';

const ModelCreate = () => {
    const navigate = useNavigate();
    const { createModel, importExternalModel, loading, error } = useModelContext();
    const [submitError, setSubmitError] = useState(null);
    const [uploadMode, setUploadMode] = useState(false);
    const [fileUploadProgress, setFileUploadProgress] = useState(0);

    const handleSubmit = async (formData) => {
        try {
            setSubmitError(null);
            await createModel(formData);
            navigate('/models');
        } catch (err) {
            console.error('创建模型失败:', err);
            setSubmitError('创建模型失败，请稍后再试');
        }
    };

    const handleFileUpload = async (file) => {
        try {
            setSubmitError(null);

            // 文件元数据
            const fileExtension = file.name.split('.').pop().toLowerCase();
            const fileName = file.name.split('.')[0];

            // 模型基本数据
            const modelData = {
                name: fileName,
                description: `导入的${fileExtension.toUpperCase()}模型`,
                color: '#3366FF',
                position: { x: 0, y: 0, z: 0 },
                rotation: { x: 0, y: 0, z: 0 },
                scale: { x: 1, y: 1, z: 1 }
            };

            // 导入模型并上传文件
            const result = await importExternalModel(file, modelData);
            console.log('导入模型结果:', result);

            // 导航到模型列表页面
            navigate('/models');
        } catch (err) {
            console.error('导入模型失败:', err);
            setSubmitError('导入模型失败，请稍后再试');
        }
    };

    const handleGoBack = () => {
        navigate('/models');
    };

    const toggleUploadMode = () => {
        setUploadMode(!uploadMode);
    };

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Box sx={{ mb: 4 }}>
                <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 2 }}>
                    <MuiLink
                        component={Link}
                        to="/"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        首页
                    </MuiLink>
                    <MuiLink
                        component={Link}
                        to="/models"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型列表
                    </MuiLink>
                    <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                        创建新模型
                    </Typography>
                </Breadcrumbs>

                <Paper
                    component={motion.div}
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    elevation={0}
                    sx={{
                        p: 3,
                        backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                        borderRadius: 4,
                        mb: 4,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <Box>
                        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                            {uploadMode ? '上传3D模型文件' : '创建新模型'}
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {uploadMode ? '上传OBJ、STL或GLB等3D模型文件' : '填写模型的基本信息'}
                        </Typography>
                    </Box>
                    <Box>
                        <Button
                            variant="outlined"
                            onClick={toggleUploadMode}
                            sx={{ mr: 2 }}
                            startIcon={uploadMode ? <ModelIcon /> : <FileUploadIcon />}
                        >
                            {uploadMode ? '切换到基本信息' : '切换到文件上传'}
                        </Button>
                        <Button
                            variant="contained"
                            startIcon={<ArrowBackIcon />}
                            onClick={handleGoBack}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                        >
                            返回列表
                        </Button>
                    </Box>
                </Paper>
            </Box>

            {submitError && (
                <Alert severity="error" sx={{ mb: 3 }}>
                    <AlertTitle>错误</AlertTitle>
                    {submitError}
                </Alert>
            )}

            {uploadMode ? (
                <Paper sx={{ p: 3, borderRadius: 2, mb: 4 }}>
                    <Typography variant="h6" gutterBottom>
                        上传模型文件
                    </Typography>
                    <Typography variant="body2" color="text.secondary" paragraph>
                        支持的文件格式: OBJ, STL, GLB, FBX
                    </Typography>
                    <Divider sx={{ my: 2 }} />

                    <FileUpload
                        onUpload={handleFileUpload}
                        isUploading={loading}
                        error={error}
                        progress={fileUploadProgress}
                    />
                </Paper>
            ) : (
                <ModelForm
                    onSubmit={handleSubmit}
                    isLoading={loading}
                    error={submitError || error}
                />
            )}
        </Container>
    );
};

export default ModelCreate; 